#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;

using octalforty.Componento.ComponentModel.Installation;
using octalforty.Componento.ComponentModel.Installation.FileSystem;
using octalforty.Componento.ComponentModel.Shell;
using octalforty.Componento.Resources;
using octalforty.Componento.Shared.SemanticModel;

namespace octalforty.Componento.ComponentModel.Commands
{
    [CommandMetadata("list")]
    public class ListCommand : ICommand
    {
        #region Private Fields
        private IRepositoryBrowserService repositoryBrowser;
        private IInstalledComponentRegistryService installedComponentRegistry;
        private IFileSystemManagerService fileSystemManager;
        #endregion

        #region Public Properties
        [Import()]
        public IRepositoryBrowserService RepositoryBrowser
        {
            [DebuggerStepThrough]
            get { return repositoryBrowser; }
            [DebuggerStepThrough]
            set { repositoryBrowser = value; }
        }

        [Import()]
        public IInstalledComponentRegistryService InstalledComponentRegistry
        {
            [DebuggerStepThrough]
            get { return installedComponentRegistry; }
            [DebuggerStepThrough]
            set { installedComponentRegistry = value; }
        }

        [Import()]
        public IFileSystemManagerService FileSystemManager
        {
            [DebuggerStepThrough]
            get { return fileSystemManager; }
            [DebuggerStepThrough]
            set { fileSystemManager = value; }
        }
        #endregion

        #region ICommand Members
        /// <summary>
        /// Executes the command with the given arguments.
        /// </summary>
        /// <param name="args"></param>
        public void Execute(params string[] args)
        {
            ArgumentParser argumentParser = new ArgumentParser(args);
            if(argumentParser.Contains("/remote"))
            {
                string repositoryUri = argumentParser.ValueOf("/source") ?? "http://repository.componento.net";
                ListRemoteComponents(new Uri(repositoryUri));
            }
            else
                ListLocalComponents();
        }
        #endregion

        private void ListRemoteComponents(Uri repositoryUri)
        {
            ComponentDescriptor[] componentDescriptors = RepositoryBrowser.GetComponentDescriptors(repositoryUri);

            foreach(ComponentDescriptor descriptor in componentDescriptors)
            {
                using(new ConsoleStylingScope(ConsoleColor.White))
                {
                    Console.Write(descriptor.Name);

                    if(descriptor.Version != null)
                        Console.Write(" {0}", descriptor.Version);

                    if(descriptor.ProjectUri != null)
                        Console.WriteLine(" ({0})", descriptor.ProjectUri);
                    else
                        Console.WriteLine();
                }

                if(!string.IsNullOrEmpty(descriptor.Description))
                    Console.WriteLine("    {0}", descriptor.Description);

                if(descriptor.Licenses != null && descriptor.Licenses.Length != 0)
                    Console.WriteLine("    {0} {1}", Properties.Resources.LicensedUnder, string.Join(", ", descriptor.Licenses));

                if(descriptor.Isas != null && descriptor.Isas.Length != 0)
                {
                    Console.WriteLine("    {0} {1}", Properties.Resources.SupportedCpuArchitectures, 
                        string.Join(", ",
                            new List<IsaType>(descriptor.Isas).
                                ConvertAll<string>(
                                    delegate(IsaType it) { return Isas.ResourceManager.GetString(it.ToString());  }).
                                ToArray()));
                } // if

                if(descriptor.Clis != null && descriptor.Clis.Length != 0)
                {
                    Console.WriteLine("    {0}", Properties.Resources.SupportedPlatforms);

                    foreach(CliEnvironment cli in descriptor.Clis)
                    {
                        Console.Write("\t{0}", Clis.ResourceManager.GetString(cli.Cli.ToString()));

                        if(cli.Version != null)
                            Console.WriteLine(" {0}", cli.Version);
                        else
                            Console.WriteLine();
                    } // foreach
                } // if

                Console.WriteLine();
            } // foreach
        }

        private void ListLocalComponents()
        {
            if(InstalledComponentRegistry.InstalledComponents.Length == 0)
            {
                Console.WriteLine(Properties.Resources.NoComponentsInstalled, FileSystemManager.CurrentDirectory);
                return;
            } // if

            foreach (ComponentReference pref in installedComponentRegistry.InstalledComponents)
                Console.WriteLine("{0} {1} ({2})", pref.Name, pref.Version, pref.Uri);
            
        }
    }
}
